package com.cg.leetcode;

import org.junit.Test;

/**
 * 203.移除链表元素
 *
 * @author cg
 * @program LeetCode->LeetCode_203
 * @create 2022-07-08 21:49
 **/
public class LeetCode_203 {

    @Test
    public void test203() {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);
        System.out.println(removeElements(head, 6));
    }

    /**
     * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
     * <p>
     * 示例 1：
     * 输入：head = [1,2,6,3,4,5,6], val = 6
     * 输出：[1,2,3,4,5]
     * <p>
     * 示例 2：
     * 输入：head = [], val = 1
     * 输出：[]
     * <p>
     * 示例 3：
     * 输入：head = [7,7,7,7], val = 7
     * 输出：[]
     * <p>
     * 提示：
     * 列表中的节点数目在范围 [0, 10^4] 内
     * 1 <= Node.val <= 50
     * 0 <= val <= 50
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        ListNode temp = new ListNode(-1, head);
        ListNode cur = head;
        ListNode per = temp;
        while (cur != null) {
            if (cur.val == val) {
                per.next = cur.next;
            } else {
                per = cur;
            }
            cur = cur.next;
        }
        return temp.next;

        //while (head != null && head.val == val) {
        //    head = head.next;
        //}
        //if (head == null) {
        //    return head;
        //}
        //ListNode current = head;
        //while (current != null) {
        //    while (current.next != null && current.next.val == val) {
        //        current.next = current.next.next;
        //    }
        //    current = current.next;
        //}
        //return head;
    }

}
